 
layui.define(['table','form','treeTable','xmSelect'], function(exports){
    var $ = layui.$
    ,form = layui.form
    ,table = layui.table
    ,setter = layui.setter
    ,admin = layui.admin
    ,treeTable = layui.treeTable
    ,xmSelect = layui.xmSelect;
      
    var renderTable;
    var field = '';
    var colsArr ;
    
    admin.req({
        url: setter.host+'/human/group/getSelectHead'
        ,type:'get'
        ,dataType:'json'
        ,done: function(res){
          //请求成功后
          if(res.status == setter.response.statusCode.status_Success){
            field = res.data;
            console.log(res);
            tableRender(res.data.field);
          }else{
        	  window.location.href = setter.host+'/error/toNoPower?msg='+res.msg;
          }
        }
    });
      
      
    function tableRender(header){
        colsArr = [
            {type: 'radio'},
            {field: 'groupId', title: 'ID',hide:(header.search("groupId") == -1)},
            {field: 'name', title: '名称',hide:(header.search("name") == -1)},
            {field: 'state', title: '级别', align:'center',hide:(header.search("state") == -1)},
            {field: 'path', title: '路径', align:'center',hide:(header.search("path") == -1)},
            {field: 'pId', title: '上级ID', align:'center',hide:true},
            {field: 'supervisor', title: '主管',align:'center',templet: '#supervisorSelect', hide:(header.search("supervisor") == -1)},
            {field: 'status', title: '状态',align:'center',templet: '#statusTpl', hide:(header.search("status") == -1)},
        ];
       
        layui.each(colsArr,function(inx,val){
            field += val.hasOwnProperty('field')?val.field:'-';
            field += ',';
        })
        field = field.substring(field.indexOf(',')+1,field.length-1);
        loadTable(colsArr,field);
    }
    function loadTable(colsArr,field){
        var treeTableWhere = {};
        treeTableWhere.headField = field;
        
        renderTable = treeTable.render({
            elem: '#LAY-group-list',
            tree: {
                iconIndex: 2,  // 折叠图标显示在第几列
                idName: 'groupId'  // 自定义id字段的名称
                ,arrowType: 'arrow1' //箭头类型
            },
            cols: colsArr,
            method:'post',
            height: 'full-15',
            contentType:"application/json; charset=utf-8",
            where:treeTableWhere,
            url: setter.host+'/adminmanager/group/getSelectBody',
            done: function(res){
            	console.log(res)
//            	var cells = document.querySelectorAll('div[id="LAY-group-list"] .layui-table-cell');
//    			for(var i = 0 ; i < cells.length ; i++ ){
//    				//cells[i].style.overflow = 'unset';
//    				cells[i].style.height = 'auto';
//    			}
    			//渲染多选
            	for (var i = 0; i < res.length; i++) {
            		var userArray = [];
            		var users = res[i].users;
            		if(users != undefined){
            			users = users.split(',');
            			for (var j = 0; j < users.length; j++) {
            				var userOne = {};
            				userOne.value = users[j].split('-')[0];
            				userOne.name = users[j].split('-')[1];
            				userOne.groupId = res[i].groupId;
            				//插入默认选中
            				if(userOne.value == res[i].supervisor){
            					userOne.selected= true;
            				}
            				userArray.push(userOne);
            				userOne = null;
            			}
            		};
            		$('#supervisor'+res[i].LAY_INDEX).parent().css('overflow','visible');
            		xmSelect.render({
    					el: '#supervisor' + res[i].LAY_INDEX, 
    					autoRow: true,
//    					model: { type: 'fixed' },
    					radio:true,
    					clickClose: true,
    					direction: 'down',
    					toolbar:{
    						show: true,
    						list: [ 'ALL', 'CLEAR', 'REVERSE' ]
    					},
    					on: function(data){
    						console.log(data);
    						layer.msg('确定修改主管吗？', {
    							  time: 0 //不自动关闭
    							  ,btn: ['确定', '取消']
    							  ,yes: function(index){
    							    layer.close(index);
    							    var sendData = {};
    							    sendData.groupId = data.arr[0].groupId;
    							    sendData.supervisor = data.arr[0].value;
    							    admin.req({
    							        url: setter.host+'/adminmanager/group/editSupervisor'
    							        ,type:'post'
    							        ,dataType:'json'
							        	,contentType: "application/json; charset=utf-8"
				                        ,data:JSON.stringify(sendData) 
    							        ,done: function(res){
    							          //请求成功后
    							        	layer.msg(res.msg);
    							        }
    							    });
    							  }
    							});
    						//arr:  当前多选已选中的数据
//    						setxmSelectTable(data.arr,index,'checkuser')
//    						table.cache['LAY-group-list'][i]['supervisor'] = valueArray.join(',');
    					},
    					filterable: true,
    					searchTips:"输入名字进行搜索",
    					data: userArray
    				})
				}
    		}
        });
    }
  
    $('.layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
  
    var active = {
        batchdel: function(){
            var checkData = renderTable.checkStatus();
                if(checkData.length === 0){
                    return layer.msg('请选择数据');
                }
            layer.prompt({
                formType: 1
                ,title: '敏感操作，请验证当前用户口令'
            }, function(value, index_prompt){
                var command = layui.sessionData('layuiSession').command;
                if(value == command){
                    layer.close(index_prompt);
                    layer.confirm('确定删除吗？', function(index_confirm) {
                        layer.close(index_confirm);
                        //因为是单选项，只能选择一个
                        if(checkData[0].hasOwnProperty('children')){
                            layer.confirm('该选择的删除数据有子菜单,确定都删除吗?', {icon: 3, title:'提示'}, function(index_del){
                                layer.close(index_del);
                                del(checkData[0].groupId,checkData[0].pId);
                            });
                        }else{
                            del(checkData[0].groupId,checkData[0].pId);
                        }
                    });
                }else{
                    layer.msg('口令错误');
                }
                
            }); 
        }
        ,add: function(){
            layer.open({
                type: 2
                ,title: '添加组织架构'
                ,content: setter.host+'/adminmanager/group/toInsert'
                ,area: ['500px', '330px']
                ,btn: ['确定', '取消']
                ,yes: function(index, layero){
                    var iframeWindow = window['layui-layer-iframe'+ index]
                    ,submitID = 'LAY-menu-add-submit'
                    ,submit = layero.find('iframe').contents().find('#'+ submitID);
                    //监听提交
                    iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
                        var indexLoad = layer.msg('添加组织架构，请稍后', {
                            icon: 16
                            ,shade: 0.01
                        });
                        admin.req({
                            url: setter.host+'/adminmanager/group/insert'
                            ,type:'post'
                            ,dataType:'json'
                            ,contentType: "application/json; charset=utf-8"
                            ,data:JSON.stringify(data.field) 
                            ,done: function(res){
                            //请求成功后
                            if(res.status == setter.response.statusCode.status_Success){
                          /*      if(data.field.groupId == '-1'){
                                    loadTable(colsArr,field);
                                }else{
                                    renderTable.refresh(data.field.groupId);
                                }*/
 								if(data.field.select == '-1'){
                                    renderTable.options.where.pid='-1';
                                    renderTable.refresh();
                                }else{
                                    renderTable.refresh(data.field.select);
                                }
                                
                            }
                            layer.close(index);
                            layer.close(indexLoad);
                            layer.msg(res.msg);
                            }
                        });
                    });  
                    submit.trigger('click');
                }
            }); 
        }
        ,edit: function(){
            var checkData = renderTable.checkStatus();
            if(checkData.length > 1){
                return layer.msg('只能选中编辑一行');
            }
            if(checkData.length ===0 ){
                return layer.msg('请选择一行数据进行编辑');
            }
 			//var editorUrl = layui.common.generate(checkData[0],setter.host+'/adminmanager/group/toEdit');
            layer.open({ 
                type: 2
                ,title: '编辑菜单'
                ,content:setter.host+'/adminmanager/group/toEdit'
                ,area: ['500px', '330px']
                ,btn: ['确定', '取消']
                ,success:function(editFrame,index){
                var iframeWindow = window['layui-layer-iframe'+ index]
                ,subBody = editFrame.find('iframe').contents();
                    //subBody.find('select[name=type]').find("option[value='button']").attr("selected",true);
                subBody.find('input[name=name]').val(checkData[0].name);
                subBody.find('input[name="oldpId"]').val(checkData[0].pId);
                    
                if(checkData[0].status=='1')
                    subBody.find('input[name=status]').attr('checked','checked');
                else
                    //subBody.find('input[name=status]');
					 subBody.find('input[name=status]').removeAttr('checked');
                    //iframeWindow.layui.form.render();
                }
                ,yes: function(index, layero){
                    var iframeWindow = window['layui-layer-iframe'+ index]
                    ,submitID = 'LAY-menu-edit-submit'
                    ,submit = layero.find('iframe').contents().find('#'+ submitID);
                        //监听提交
                    iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
						console.log(data)
//                       data.field.oldpId = checkData[0].pId;
						data.field.pId = checkData[0].pId;
                        data.field.groupId = checkData[0].groupId;
                        data.field.oldpath = checkData[0].path;
                        admin.req({
                        url: setter.host+'/adminmanager/group/edit'
                        ,type:'post'
                        ,dataType:'json'
                        ,contentType: "application/json; charset=utf-8"
                        ,data:JSON.stringify(data.field)  
                        ,done: function(res){                            //请求成功后
                            if(res.status == setter.response.statusCode.status_Success){
                            	loadTable(colsArr,field);
//                                if(data.field.pId == '-1'){
//                                    loadTable(colsArr,field);
//                                }else{
//                                    renderTable.refresh(data.field.pId);
//                                }
                                
                            }
                            layer.close(index);
                            layer.msg(res.msg);
                        }
                        });
                    });  
                        submit.trigger('click');
                }
            });
        }
        ,editUser: function(){
            var checkData = renderTable.checkStatus();
            if(checkData.length > 1){
                return layer.msg('只能选中编辑一行');
            }
            if(checkData.length ===0 ){
                return layer.msg('请选择一行数据进行编辑');
            }
            layer.open({
	  	          type: 2
	  	          ,title: '维护组织人员'
	  	          ,content: setter.host+'/adminmanager/group/toeditUser'
	  	          ,area: ['515px', '560px']
	  	          ,btn: ['确定', '取消']
	  	    	  ,success:function(editFrame,index){
	  	    		var iframeWindow = window['layui-layer-iframe'+ index]
	  	    		,subBody = editFrame.find('iframe').contents()
	  	    		subBody.find('#groupId').val(checkData[0].groupId);
	  	    	  }
	  	          ,yes: function(index, editFrame){
		  	        	var iframeWindow = window['layui-layer-iframe'+ index]
	                    ,subBody = editFrame.find('iframe').contents();
		  	        	var changeUser = JSON.parse(subBody.find('#changeUser').val());
		  	        	var userArray = [];
		  	        	for(var el in changeUser){
		  	        		var groupId = changeUser[el].groupId.join(',');
		  	        		var userOne = {};
		  	        		userOne.groupId = groupId;
		  	        		userOne.userId = changeUser[el].value;
		  	        		userOne.name = changeUser[el].title;
		  	        		userArray.push(userOne);
		  	        		groupId = null;
		  	        		userOne = null;
		  	        	}
		  	        	console.log(changeUser)
		  	        	var sendData = {};
		  	        	sendData.groupId = checkData[0].groupId;
		  	        	sendData.userArray = JSON.stringify(userArray);
		  	        	 console.log(sendData)
	                     admin.req({
		                     url: setter.host+'/adminmanager/group/editUser'
		                     ,type:'post'
		                     ,dataType:'json'
		                     ,contentType: "application/json; charset=utf-8"
		                     ,data:JSON.stringify(sendData)  
		                     ,done: function(res){
		                         //请求成功后
		//                         if(res.status == setter.response.statusCode.status_Success){
		//                         	loadTable(colsArr,field);
		//                             
		//                         }
		                         layer.msg(res.msg);
		                         layer.close(index);
		                     }
	                     });
                        layer.close(index);
                        
	  	          }
	  	    });
            
            
        }
    }
    function del(groupId,pId){
        var indexLoad = layer.msg('删除组织机构，请稍后', {
            icon: 16
            ,shade: 0.01
        });
        admin.req({
            url: setter.host+'/adminmanager/group/batchdel'
            ,type:'post'
            ,contentType: "application/json; charset=utf-8"
            ,data:'{"groupId":"'+groupId+'","pId":"'+pId+'"}'
            ,done: function(res){
            //请求成功后
            if(res.status == setter.response.statusCode.status_Success){
                    if(pId == '-1'){
                        loadTable(colsArr,field);
                    }else{
                        renderTable.refresh(pId);
                    }
                    
                }
            layer.close(indexLoad);
            layer.msg(res.msg);
            }
        });
    }
    //对外暴露的接口
    exports('select', {});
  });